//app.js
App({
  cart: [],
  user: [],
  login () {
    wx.request({
      url: 'http://rap2api.taobao.org/app/mock/120484/api/v1/login',
      data: '',
      header: {},
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        this.user = res.data.data
        this.snycUserToStorage()
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  logout () {
    this.user = []
    this.snycUserToStorage()
  },
  addToCart(cartItem) {
    let {count, prod} = cartItem
    let {
      title,
      qunTitle,
      price,
      image,
      id
    } = prod 
    const isInCart = this.cart.some(item => item.id === id)
    if (isInCart) {
      this.cart = this.cart.map(item => {
        item.count += count
        return item
      })
    } else {
      this.cart = this.cart.concat({
        id,
        image,
        title,
        qunTitle,
        price,
        count,
        checked: false
      })
    }
    this.snycCartToStorage()
  },
  snycCartToStorage () {
    wx.setStorageSync('cart', this.cart)
  },
  snycUserToStorage() {
    wx.setStorageSync('user', this.user)
  },
  add(id) {
    this.cart = this.cart.map(item => {
      if (item.id === id) {
        item.count++
      }
      return item
    })
  },
  reduce(id) {
    this.cart = this.cart.map(item => {
      if (item.id === id) {
        if (item.count !== 1) {
          item.count--
        } else {
          wx.showToast({
            title: '数量已为最小',
            icon: 'none',
            duration: 2000
          })
        }
      }
      return item
    })
  },
  onLaunch: function () {
    this.cart = wx.getStorageSync('cart') || []
    this.user = wx.getStorageSync('user') || []
    // this.setBadge()
    // 展示本地存储能力
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    sysWidth: wx.getSystemInfoSync().windowWidth, //图片宽度
  }
})